<script setup>
import { get, dalImg, post, del, patch, serverUrl } from '../../utils/request'
import { reactive, ref, toRaw } from 'vue';
import { cloneDeep } from 'lodash-es';
import { CheckOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons-vue';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons-vue';
const dataSource = ref([]);
const isEnd = ref(false)
const aurl = ref('')
const num = ref(0)
const a = ref([])
const upid = ref('')
const drug = (page = 1) => {
    get('/admin/medicine_categories', { page, per: 10 }).then(res => {
        console.log(res);
        total.value = res.data.total
        dataSource.value = res.data.list.map((item, index) => ({
            key: item.id,
            sort: index + 1,
            name: item.name,
            desc: item.desc,
            image: dalImg(item.image),
            createdAt: new Date(item.createdAt).toLocaleString(),
        }));
    })
}
drug()
const columns = [
    {
        title: '编号',
        dataIndex: "sort",
    },
    {
        title: '名称',
        dataIndex: "name",
    },
    {
        title: '简介',
        dataIndex: 'desc',
    },
    {
        title: '图片',
        dataIndex: 'image',
    },
    {
        title: '创建时间',
        dataIndex: 'createdAt',
    },
    {
        title: '删除',
        dataIndex: 'operation',
    },
];
// const count = computed(() => dataSource.value.length + 1);
const editableData = reactive({});
const edit = key => {
    editableData[key] = cloneDeep(dataSource.value.filter(item => key === item.key)[0]);
};
const save = key => {
    Object.assign(dataSource.value.filter(item => key === item.key)[0], editableData[key]);
    delete editableData[key];
};
const onDelete = key => {
    del('/admin/medicine_categories/' + key).then(res => {
        dataSource.value = dataSource.value.filter(item => item.key !== key);
    })
};
const handleAdd = () => {
    isEnd.value = !isEnd.value
    num.value = 1
    formState.value.name = ""
    formState.value.desc = ""
    aurl.value = ""
    // const newData = {
    //     key: `${count.value}`,
    //     name: `Edward King ${count.value}`,
    //     age: 32,
    //     address: `London, Park Lane no. ${count.value}`,
    // };

    // dataSource.value.push(newData);
};
// 修改
const upHandle = (key) => {
    isEnd.value = !isEnd.value
    num.value = 2
    a.value = dataSource.value.filter(item => item.key == key)
    formState.value = {
        name: a.value[0].name,
        desc: a.value[0].desc,
        image: a.value[0].image
    }
    upid.value = key
}
// 图片上传
import { message } from 'ant-design-vue';
function getBase64(img, callback) {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
}
const fileList = ref([]);
const loading = ref(false);
const imageUrl = ref('');
const handleChange = info => {
    if (info.file.status === 'uploading') {
        loading.value = true;
        return;
    }
    if (info.file.status === 'done') {
        console.log(info.file.response.data);
        // Get this url from response in real world.
        aurl.value = info.file.response.data
        getBase64(info.file.originFileObj, base64Url => {
            imageUrl.value = base64Url;
            loading.value = false;
        });
    }
    if (info.file.status === 'error') {
        loading.value = false;
        message.error('upload error');
    }
};
const beforeUpload = file => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
        message.error('You can only upload JPG file!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
        message.error('Image must smaller than 2MB!');
    }
    return isJpgOrPng && isLt2M;
};
// 表单
const formState = ref({
    name: '',
    desc: '',
});
const onSubmit = () => {
    console.log('submit!', toRaw(formState.value));
    const data = {
        name: formState.value.name,
        desc: formState.value.desc,
        image: aurl.value
    }
    if (num.value == 1) {
        post('/admin/medicine_categories', data).then(res => {
            dataSource.value.push(data)
            isEnd.value = false
            drug()
        }).catch(error => {
            console.log('报错' + error);
        })
    } else if (num.value == 2) {
        const data = {
            name: formState.value.name,
            desc: formState.value.desc,
            image: aurl.value
        }
        patch('/admin/medicine_categories/' + upid.value, data).then(res => {
            isEnd.value = false
            drug()
        }).catch(error => {
            console.log('报错' + error);
        })
    }
    formState.value.name = ""
    formState.value.desc = ""
    aurl.value = ""
};
// 分页
const total = ref()
const current = ref(10);
const fenye = (page) => {
    console.log(page);
    drug(page)
}
const keyHandle = () => {
    const name = formState.value.name
    get('/admin/medicine_categories/' + name).then(res => {
        dataSource.value = dataSource.value.filter(item => {
            return item.name.indexOf(name) != -1
        });
    })
}
</script>
<template>
    <div class="drug">
        <div class="chaxu">
            <a-button class="editable-add-btn" style="margin-bottom: 8px" @click="handleAdd">增加</a-button>
            <a-form-item label="名称">
                <a-input v-model:value="formState.name" @keyup.enter="keyHandle" />
            </a-form-item>
        </div>
        <a-table bordered :data-source="dataSource" :columns="columns" :pagination="false">
            <template #bodyCell="{ column, text, record }">
                <template v-if="column.dataIndex === 'name'">
                    <div class="editable-cell">
                        <div v-if="editableData[record.key]" class="editable-cell-input-wrapper">
                            <a-input v-model:value="editableData[record.key].name" @pressEnter="save(record.key)" />
                            <check-outlined class="editable-cell-icon-check" @click="save(record.key)" />
                        </div>
                        <div v-else class="editable-cell-text-wrapper">
                            {{ text || ' ' }}
                            <!-- <edit-outlined class="editable-cell-icon" @click="edit(record.key)" /> -->
                        </div>
                    </div>
                </template>
                <template v-if="column.dataIndex === 'image'">
                    <div class="editable-cell">
                        <div v-if="editableData[record.key]" class="editable-cell-input-wrapper">
                            <a-input v-model:value="editableData[record.key].image" @pressEnter="save(record.key)" />
                            <check-outlined class="editable-cell-icon-check" @click="save(record.key)" />
                        </div>
                        <div v-else class="editable-cell-text-wrapper">
                            <img :src="text" class="editable-cell-image" />
                            <!-- <edit-outlined class="editable-cell-icon" @click="edit(record.key)" /> -->
                        </div>
                    </div>
                </template>
                <template v-else-if="column.dataIndex === 'operation'">
                    <a-popconfirm v-if="dataSource.length" title="是否确认删除" @confirm="onDelete(record.key)">
                        <a>
                            <DeleteOutlined style="color: white; background-color: red; font-size: 20px; padding: 5px;" />
                        </a>
                    </a-popconfirm>
                    <a>&emsp;
                        <EditOutlined @click="upHandle(record.key)"
                            style="color:white;background-color: rgb(12, 67, 229); font-size: 20px; padding: 5px;" />
                    </a>
                </template>
            </template>
        </a-table>
        <a-pagination v-model:current="current" :total="total" show-less-items @change="fenye" />
        <!-- 表单 -->
        <div class="form" v-if="isEnd">
            <a-form :model="formState" :label-col="labelCol" :wrapper-col="wrapperCol" style="width: 600px;">
                <a-form-item label="名称">
                    <a-input v-model:value="formState.name" />
                </a-form-item>
                <a-form-item label="简介">
                    <a-textarea :rows="4" v-model:value="formState.desc" />
                </a-form-item>
                <a-upload v-model:file-list="fileList" name="file" list-type="picture-card" class="avatar-uploader"
                    :show-upload-list="false" :action="serverUrl + '/common/upload'" :before-upload="beforeUpload"
                    @change="handleChange">
                    <img v-if="imageUrl" :src="imageUrl" alt="avatar" />
                    <div v-else>
                        <loading-outlined v-if="loading"></loading-outlined>
                        <plus-outlined v-else></plus-outlined>
                        <div class="ant-upload-text">图片上传</div>
                    </div>
                </a-upload>
                <a-form-item :wrapper-col="{ span: 14, offset: 4 }">
                    <a-button type="primary" @click="onSubmit">确认</a-button>
                    <a-button style="margin-left: 10px" @click="isEnd = false">取消</a-button>
                </a-form-item>
            </a-form>
        </div>
    </div>
</template>
<style scoped>
.drug {
    height: 100%;
    overflow: auto;
}

.editable-add-btn {
    background-color: rgb(17, 222, 212);
    color: white;
    margin-right: 20px;
}

.drug img {
    width: 30px;
}

.form {
    padding: 10px;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    background-color: rgba(215, 215, 215, 0.87);
    z-index: 100px;
}

.chaxu {
    display: flex;
}
</style>